package com.bookpavilion.comment.controller;


import com.bookpavilion.comment.pojo.Comment;
import com.bookpavilion.comment.service.CommentService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @PostMapping
    public Result save(@RequestBody Comment comment) {
        commentService.addGoodsComment(comment);
        return new Result(true, StatusCode.OK, "提交成功");
    }

    @GetMapping(value = "/goodsId/{articleid}/{page}/{size}")
    public Result findByGoodsId(@PathVariable String goodsId,@PathVariable int page,@PathVariable int size) {
        Page<Comment> pageData = commentService.findCommentByGoodsId(goodsId, page, size);
        return new Result(true, StatusCode.OK, "查询成功",new PageResult<Comment>(pageData.getTotalElements(), pageData.getContent()));
    }

    @GetMapping("/parentId/{parentId}/{page}/{size}")
    public Result findCommentsByParentId(@PathVariable String parentId,@PathVariable int page,@PathVariable int size){
        Page<Comment> pageData = commentService.findCommentByParentId(parentId, page, size);
        return new Result(true,StatusCode.OK,"查询成功",new PageResult<Comment>(pageData.getTotalElements(), pageData.getContent()));
    }
    @GetMapping
    public Result findAllGoodsComment(){
        return new Result(true,StatusCode.OK,"查询成功",commentService.findAllGoodsComment());
    }

    @DeleteMapping("/{id}")
    public Result deleteGoodsCommentById(@PathVariable String id){
        try {
            commentService.findCommentById(id);
        } catch (Exception e) {
            return new Result(false,StatusCode.ERROR,"不存在该记录");
        }

        commentService.deleteGoodsComment(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    @GetMapping("/{id}")
    public Result findCommentById(@PathVariable String id){
        Comment comment=null;
        try {
            comment =commentService.findCommentById(id);
        } catch (Exception e) {
            return new Result(false,StatusCode.ERROR,"不存在该记录");
        }

        return new Result(true,StatusCode.OK,"查询成功",comment);
    }
}
